package com.zj.util;

import cn.hutool.core.lang.Snowflake;

import java.util.List;

/**
 * 雪花算法工具类
 */
public class SnowFlakeIdGenrator {
    // 数据中心id
    private Long dataCenterId;
    // 工作节点id
    private Long workerId;
    // 序列号
    private Long sequence;

    //这是hutool提供的方法
    private final Snowflake snowflake;


    //1.雪花算法构造器
    public SnowFlakeIdGenrator(Long dataCenterId, Long workerId) {
        this.dataCenterId = dataCenterId;
        this.workerId = workerId;
        this.sequence = 0L;

        this.snowflake = new Snowflake(workerId,dataCenterId);
    }

    //2.生成一个id
    public synchronized Long nextId(){
        //测试异常
//        boolean a=true;
//        if (a){
//            throw new RuntimeException("测试异常");
//        }
        return snowflake.nextId();
    }

    //3.生成多个id
    private final int batchSize = 1000;  //最大1000个
    // 批量生成id
    public List<Long> nextIds(int batchSize) {
        if(batchSize > this.batchSize){
            batchSize = this.batchSize;
        }
        List<Long> ids = new java.util.ArrayList<>();
        for (int i = 0; i < batchSize; i++) {
            ids.add(nextId());
        }
        return ids;
    }

    /**
     *解析时间戳
     * @param id
     * @return
     */
    public long parseTimeStamp(long id){
        return snowflake.getGenerateDateTime(id);
    }

    /**
     * 解析数据中心id
     * @param id
     * @return
     */
    public long parseDataCenterId(long id){
        return snowflake.getDataCenterId(id);
    }

    /**
     * 解析工作节点id
     * @param id
     * @return
     */
    public long parseWorkerId(long id){
        return snowflake.getWorkerId(id);
    }


//    public static void main(String[] args) {
//        SnowFlakeIdGenrator snowFlakeIdGenrator = new SnowFlakeIdGenrator(0L,1L);
//        long id = snowFlakeIdGenrator.nextId();
//        System.out.println(id);
//        System.out.println(snowFlakeIdGenrator.parseTimeStamp(id));
//        System.out.println(snowFlakeIdGenrator.parseDataCenterId(id));
//        System.out.println(snowFlakeIdGenrator.parseWorkerId(id));
//
//    }
}
